<template>
  <NewCard :title="getTitle()">
    <div class="handleSet">
      <div class="hint">
        <span>为保障您的账户安全</span>
        <p>进行操作前需验证身份</p>
      </div>
      <div class="selectVerify">
        <span>请选择一种验证方式</span>
        <!-- 只有一种校验方式的时候拉长 -->
        <ul :class="['', undefined, null].includes(userInfo.email)?'oneCheck':''">
          <li :class="isTelOrEmail=='1' ? 'isActive' : ''" @click="telVerify">
            <div class="verifyIcon">
              <svg-icon icon-class="tel" />
            </div>
            <div class="verifyInfo">
              <p>{{ userInfo.phonenumber }}</p>
              <span>通过手机验证码验证身份</span>
            </div>
          </li>
          <li :class="isTelOrEmail=='2' ? 'isActive' : ''" @click="emailVerify" v-if="!['', undefined, null].includes(userInfo.email)">
            <div class="verifyIcon">
              <svg-icon icon-class="email" />
            </div>
            <div class="verifyInfo">
              <p>{{ userInfo.email }}</p>
              <span>通过邮箱验证码验证身份</span>
            </div>
          </li>
        </ul>
      </div>
      <!-- 验证手机和邮箱 -->
      <div class="verifyForm">
        <el-form ref="form" label-width="130px" label-position="left">
          <div class="form1" v-if="isTelOrEmail=='1'">
            <el-form-item label="手机号" style="margin-bottom: 12px">
              <el-input
                :disabled="!isInputPhonenumber"
                v-model="oldPhonenumber"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机验证码">
              <el-input
                @input="verifyCodeFn"
                v-model="code"
                placeholder="请输入手机验证码"
              >
                <el-button slot="suffix"
                  ><span
                    @click="obtainVerifyCode"
                    :style="{
                      color: verifyContent.disabled ? 'grey' : '#f87a23',
                      cursor: verifyContent.disabled ? 'unset' : 'pointer',
                    }"
                  >
                    {{ verifyContent.text }}
                  </span></el-button>
              </el-input>
            </el-form-item>
          </div>
          <!--  !['', undefined, null].includes($store.getters.email) = 邮箱如果为空就不显示，让它直接绑定新的邮箱 -->
          <div class="form2"
            v-if="isTelOrEmail=='2' && !['', undefined, null].includes(userInfo.email)">
            <el-form-item label="邮箱" style="margin-bottom: 12px">
              <el-input
                :disabled="!isInputEmail"
                v-model="oldEmail"
                @blur="blurEmailRul"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱验证码">
              <el-input
                @input="verifyEmailCodeFn"
                v-model="verifyEmail.code"
                placeholder="请输入邮箱验证码"
              >
                <el-button slot="suffix"
                  ><span
                    @click="sendEmalCode"
                    :style="{
                      color: emailObj.disabled ? 'grey' : '#f87a23',
                      cursor: emailObj.disabled ? 'unset' : 'pointer',
                    }"
                  >
                    {{ emailObj.text }}
                  </span></el-button
                >
              </el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template v-if="isPass || ['', undefined, null].includes(userInfo.email) && isTelOrEmail=='2'">
        <!-- 验证成功提示 -->
        <div class="verifyHint">
          <!-- (!isTelOrEmail &&!['', undefined, null].includes(userInfo.email)) ||isTelOrEmail  是邮箱且不等于空。如果是手机号直接通过 -->
          <p class="vSuccess"
            v-if="
              (isTelOrEmail=='2' &&
                !['', undefined, null].includes(userInfo.email)) ||
              isTelOrEmail=='1'
            ">
            <i class="el-icon-success"></i>已通过身份验证，请绑定您的新{{getNewWhat()}}
          </p>
        </div>
        <!-- 修改手机和邮箱 -->
        <div class="verifyForm setForm">
          <el-form ref="form" label-width="130px" label-position="left">
            <div class="form1" v-if="setTOrE=='1'">
              <el-form-item label="新手机号">
                <el-input
                  v-model="newPhoneObj.phonenumber"
                  placeholder="请输入新手机号码"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="手机验证码">
                <el-input
                  v-model="newPhoneObj.code"
                  placeholder="请输入手机验证码"
                >
                  <el-button slot="suffix"
                    ><span
                      @click="newObtainVerifyCode('new')"
                      :style="{
                        color: newVerifyContent.disabled ? 'grey' : '#f87a23',
                        cursor: newVerifyContent.disabled ? 'unset' : 'pointer',
                      }"
                    >
                      {{ newVerifyContent.text }}
                    </span></el-button
                  >
                </el-input>
              </el-form-item>
            </div>
            <div class="form2" v-else-if="setTOrE=='2'">
              <el-form-item label="新邮箱">
                <el-input
                  v-model="updateEmail.email"
                  @blur="blurEmailRul"
                  placeholder="请输入新邮箱"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="邮箱验证码">
                <el-input
                  v-model="updateEmail.code"
                  placeholder="请输入邮箱验证码"
                >
                  <el-button slot="suffix"
                    ><span
                      @click="newSendEmailCode"
                      :style="{
                        color: updateEmailDown.disabled ? 'grey' : '#f87a23',
                        cursor: updateEmailDown.disabled ? 'unset' : 'pointer',
                      }"
                    >
                      {{ updateEmailDown.text }}
                    </span></el-button
                  >
                </el-input>
              </el-form-item>
            </div>
            <div class="form3" v-else-if="setTOrE=='3'">
              <el-form-item label="新密码">
                <el-input
                  v-model="newPassword"
                  show-password
                  placeholder="请输入8~18位字符(需包含数字、字母)">
                </el-input>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </template>
      <!-- 确认按钮 -->
      <div class="setBtn" v-if="isPass || ['', undefined, null].includes(userInfo.email) && isTelOrEmail=='2'">
        <el-button round @click="$emit('EventSucess', true)">取消</el-button>
        <el-button round class="addBtn" @click="success">完成</el-button>
      </div>
    </div>
  </NewCard>
</template>

<script>
import debounce from "lodash/debounce";
import {
  getUpdatePhonenumberApi,
  getProfileUpdateEmailApi,
  setUserProfileUpdatePwdApi,
} from "@/BMViews/api/user/profile.js";
import NewCard from "@/wss/components/newCard.vue";

import {
  getEmailCodeApi,
  getVerificationMailCodeApi,
  getOrderListApi,
  getVerificationCodeApi,
} from "@/BMViews/api/login.js";
import { mapGetters } from "vuex";

export default {
  name: "setTelOrEmail",
  components: { NewCard },
  props: {
    setTOrE:{
      type: String,
    },
    isSetPwd:{
      type: Boolean,
    },
  },
  data() {
    return {
      // 老的邮箱
      oldEmail: "",
      newPhoneObj: {
        phonenumber: "",
        code: "",
      },
      // 新手机号码
      newPhone: "",
      // 验证码
      code: "",
      // 是否验证通过
      isPass: false,
      // 获取验证码按钮
      verifyContent: {
        disabled: false,
        text: "获取验证码",
        time: 60,
      },
      // 新箱倒计时
      newVerifyContent: {
        disabled: false,
        text: "获取验证码",
        time: 60,
      },
      verifyEmail: { email: "", code: "" },
      // 邮箱倒计时
      emailObj: {
        disabled: false,
        text: "获取验证码",
        time: 60,
      },
      // 更新邮箱倒计时
      updateEmailDown: {
        disabled: false,
        text: "获取验证码",
        time: 60,
      },
      // 修改邮箱
      updateEmail: {
        email: "",
        code: "",
      },
      // 旧的电话号码
      oldPhonenumber: "",
      // 旧的邮箱
      oldEmail: "",
      // 旧的邮箱是否可以被输入
      isInputEmail: "",
      // 旧的手机是否可以被输入

      newPassword:'',// 修改的新密码

      isInputPhonenumber: "",
      // 邮箱验证码
      emailCode: "",
      isTelOrEmail: '1', //1选择手机验证 2选择邮箱验证
      ableInput: "",
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    setTOrE(newVal, oldVal) {
      this.isPass = false //切换的时候关掉验证通过
      this.newPhoneObj.code = '' //切换的时候清掉验证码
      this.verifyEmail.code = '' //切换的时候清掉验证码
      // this.isTelOrEmail = newVal; //获取当前状态 1选择手机验证 2选择邮箱验证 3修改密码
    },
  },
  mounted() {
    this.isPass = false //切换的时候关掉验证通过
    // this.isTelOrEmail = this.setTOrE //获取当前状态 1选择手机验证 2选择邮箱验证 3修改密码

    const arr = [null, "", undefined];
    this.oldEmail = this.userInfo.email;
    this.oldPhonenumber = this.userInfo.phonenumber;
    // 是否邮箱为空
    this.isInputEmail = arr.includes(this.oldEmail) ? true : false;
    this.isInputPhonenumber = arr.includes(this.oldPhonenumber) ? true : false;
  },
  methods: {
    // 获取标题
    getTitle(){
      if(this.setTOrE=='1'){
        return '更改手机号'
      }else if(this.setTOrE=='2'){
        return '更改邮箱'
      }else if(this.setTOrE=='3'){
        return '更改密码'
      }
    },

    // 获取 已通过身份验证，请绑定您的新"?" 什么
    getNewWhat(){
      if(this.setTOrE=='1'){
        return '手机号'
      }else if(this.setTOrE=='2'){
        return '邮箱'
      }else if(this.setTOrE=='3'){
        return '密码'
      }
    },

    // 新手机发送验证码
    newObtainVerifyCode: debounce(async function (params) {
      var self = this;
      if (self.newVerifyContent.disabled) return;
      if (self.validePhone(this.newPhoneObj.phonenumber)) {
        // 发送短信接口请求
        let { code } = await getOrderListApi(this.newPhoneObj.phonenumber);
        if (code != 200) return;
        self.newcountDown();
        this.$message({
          type: "success",
          message: "已发送",
        });
      }
    }, 300),

    // 倒计时方法
    newcountDown() {
      var time = 60;
      this.newVerifyContent.disabled = true;
      this.newVerifyContent.text = `重新获取(${time}s)`;
      var timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.newVerifyContent.disabled = false;
          this.newVerifyContent.text = "获取验证码";
        } else {
          this.newVerifyContent.disabled = true;
          this.newVerifyContent.text = `重新获取(${time}s)`;
          time--;
          // this.verifyContent.time--;
        }
      }, 1000);
    },
    // 验证验证码
    verifyCodeFn: debounce(async function(){
      if (this.code == "" || this.code.length != 4) return;
      let { code } = await getVerificationCodeApi({
        code: this.code,
        mobile: this.userInfo.phonenumber,
      });
      if (code != 200) return;

      this.isPass = true;
    },300),

    //点击手机验证
    telVerify() {
      this.isTelOrEmail = '1';
      // this.$emit("changeEtTOrE", '1');
    },
    //点击邮箱验证
    emailVerify() {
      this.isTelOrEmail = '2';
      // this.$emit("changeEtTOrE", '2');
    },
    obtainVerifyCode: debounce(async function (params) {
      if (this.verifyContent.disabled) return;
      const phonenumber = this.userInfo.phonenumber;
      // 防抖

      var self = this;
      if (self.verifyContent.disabled) {
        return;
      }
      if (self.validePhone(phonenumber)) {
        // 发送短信接口请求
        let { code } = await getOrderListApi(phonenumber);
        if (code != 200) return;
        self.countDown();
        this.$message({
          type: "success",
          message: "已发送",
        });
      }
    }, 300),
    // async obtainVerifyCode(isnew) {
    //   if (this.verifyContent.disabled) return;
    //   const phonenumber = this.userInfo.phonenumber;
    //   // 防抖
    //   debounce(async () => {
    //     var self = this;
    //     if (self.verifyContent.disabled) {
    //       return;
    //     }
    //     if (self.validePhone(phonenumber)) {
    //       // 发送短信接口请求
    //       let { code } = await getOrderListApi(phonenumber);
    //       if (code != 200) return;
    //       this.$message({
    //         type: "success",
    //         message: "已发送",
    //       });
    //       self.countDown();
    //     }
    //   }, 500)();
    // },
    // 倒计时方法
    countDown() {
      var time = 60;
      this.verifyContent.disabled = true;
      this.verifyContent.text = `重新获取(${time}s)`;
      var timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.verifyContent.disabled = false;
          this.verifyContent.text = "获取验证码";
        } else {
          this.verifyContent.disabled = true;
          this.verifyContent.text = `重新获取(${time}s)`;
          time--;
          // this.verifyContent.time--;
        }
      }, 1000);
    },
    // 验证手机号
    validePhone(phonenumber) {
      console.log(!/^1[3456789]\d{9}$/.test(phonenumber));
      if (["", null, undefined].includes(phonenumber)) {
        this.$message({
          type: "warning",
          message: "请输入手机号",
        });
        return false;
      } else if (!/^1[3456789]\d{9}$/.test(phonenumber)) {
        this.$message({
          type: "warning",
          message: "请输入正确的手机号码",
        });
        return false;
      } else {
        return true;
      }
    },
    // ===========================================上手机下邮箱========================================

    // 完成
    sendEmalCode: debounce(async function (params) {
      if (this.emailObj.disabled) return;
      var self = this;

      // 发送短信接口请求
      let { code } = await getEmailCodeApi(this.oldEmail);
      if (code != 200) return;
      self.countDownEmail();
      this.$message({
        type: "success",
        message: "已发送",
      });
    }, 300),

    // 邮箱的验证
    blurEmailRul() {
      let email = this.updateEmail.email
      let reg = /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (email == "") {
        this.$message({ type: "warning", message: "邮箱不能为空！" });
      } else {
        if (!reg.test(email)) {
          this.$message({ type: "warning", message: "请输入有效的邮箱！" });
        }
      }
    },

    // 邮箱倒计时方法
    countDownEmail() {
      var time = 60;
      this.emailObj.disabled = true;
      this.emailObj.text = `重新获取(${time}s)`;
      var timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.emailObj.disabled = false;
          this.emailObj.text = "获取验证码";
        } else {
          this.emailObj.disabled = true;
          this.emailObj.text = `重新获取(${time}s)`;
          time--;
          // this.verifyContent.time--;
        }
      }, 1000);
    },
    // 更新邮箱倒计时方法
    updatecountDownEmail() {
      var time = 60;
      this.updateEmailDown.disabled = true;
      this.updateEmailDown.text = `重新获取(${time}s)`;
      var timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.updateEmailDown.disabled = false;
          this.updateEmailDown.text = "获取验证码";
        } else {
          console.log(this.updateEmailDown, "1212");
          this.updateEmailDown.disabled = true;
          this.updateEmailDown.text = `重新获取(${time}s)`;
          time--;
          // this.verifyContent.time--;
        }
      }, 1000);
    },
    // 验证邮箱验证码
    async verifyEmailCodeFn() {
      const verifyEmail = this.verifyEmail;
      if (verifyEmail.code == "" || verifyEmail.code.length != 4) return;
      verifyEmail.email = this.oldEmail;

      let { code } = await getVerificationMailCodeApi(verifyEmail);
      if (code != 200) return;
      this.isPass = true;
    },
    // 新邮箱的验证码
    newSendEmailCode: debounce(
      async function () {
        if (this.updateEmailDown.disabled) return;
        // /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
        let emailRegExp = /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if (!emailRegExp.test(this.updateEmail.email)) {
          this.$message({
            type: "warning",
            message: "邮箱不合法",
          });
          return;
        }
        let self = this;

        // 发送短信接口请求
        let { code } = await getEmailCodeApi(this.updateEmail.email);
        if (code != 200) return;
        self.updatecountDownEmail();
        this.$message({
          type: "success",
          message: "已发送",
        });
      },300
    ),

    // ---------------------修改密码的接口----------------------
    async setUserProfileUpdatePwd(){
      const newPassword = this.newPassword
      let result = await setUserProfileUpdatePwdApi({newPassword})
      if(result.code==200){
        this.$message({
          type: "success",
          message: result.msg,
        });
      }
    },

    async success() {
      // 更新手机号
      if (this.setTOrE=='1') {
        
        const newPhoneObj = this.newPhoneObj,
          userInfo = this.userInfo;
        if (newPhoneObj.phonenumber == userInfo.phonenumber) {
          newPhoneObj.phonenumber = "";
        }
        let { code, msg } = await getUpdatePhonenumberApi(newPhoneObj);

        if (code != 200) return;
        userInfo.phonenumber = newPhoneObj.phonenumber;
        this.$message({
          type: "success",
          message: msg,
        });
        this.$store.dispatch("GetInfo").then(() => {
          this.$emit("EventSucess", true)
        }).catch(() => {});

      } else if(this.setTOrE=='2') {

        // 更新邮箱
        const updateEmail = this.updateEmail,
          userInfo = this.userInfo;
        if (updateEmail.email == userInfo.email) return;
        let { code, msg } = await getProfileUpdateEmailApi(this.updateEmail);
        if (code != 200) return;
        userInfo.email = updateEmail.email;
        this.$message({
          type: "success",
          message: msg,
        });
        this.$store.dispatch("GetInfo").then(() => {
          this.$emit("EventSucess", true)
        }).catch(() => {});
        

      }else if(this.setTOrE=='3'){

        let reg = /^(?=.*[0-9])(?=.*[a-zA-Z]).{8,18}$/;
        if(!reg.test(this.newPassword)){
          this.$message({type: "warning", message: '请输入8~18位字符(需包含数字、字母)'});
        }else{
          this.setUserProfileUpdatePwd() // 修改密码的接口
          this.$emit("EventSucess", true);
        }

      }
    },
  },
};
</script>

<style scoped>
ul,
p {
  list-style: none;
  margin: 0;
  padding: 0;
}
/* 更改手机号邮箱 */
.handleSet {
  padding: 20px 0;
  margin-bottom: 60px;
}
.hint {
  margin-bottom: 40px;
}
.hint > span {
  display: block;
  font-size: 14px;
  color: #999;
  margin-bottom: 12px;
}
.hint p {
  font-size: 20px;
  font-weight: bold;
  color: #222;
}

.selectVerify {
  margin-bottom: 30px;
}
.selectVerify > span {
  display: block;
  font-size: 14px;
  color: #999;
  margin-bottom: 15px;
}
.selectVerify ul {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.selectVerify ul.oneCheck >li{
  width: 100%;
}
.selectVerify ul > li {
  display: flex;
  align-items: center;
  width: 48.5%;
  padding: 20px;
  background-color: #f4f5f8;
  border-radius: 8px;
  transition: all 0.3s;
}
.selectVerify ul > li .verifyIcon {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 18px;
  width: 48px;
  height: 48px;
  background-color: #e2e2e4;
  border-radius: 50%;
  transition: all 0.3s;
}
.selectVerify ul > li .verifyIcon > svg {
  font-size: 20px;
  color: #a7a7b2;
  transition: all 0.3s;
}

.selectVerify ul > li .verifyInfo {
  flex-grow: 1;
}
.selectVerify ul > li .verifyInfo > p {
  font-weight: bold;
  color: #222;
  font-size: 16px;
}
.selectVerify ul > li .verifyInfo > span {
  display: block;
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

.selectVerify ul > li.isActive {
  background-color: #39486f;
}
.selectVerify ul > li.isActive .verifyIcon {
  background-color: #fff;
}
.selectVerify ul > li.isActive .verifyIcon > svg {
  color: #39486f;
}
.selectVerify ul > li.isActive .verifyInfo > p {
  color: #fff;
}
.selectVerify ul > li.isActive .verifyInfo > span {
  color: #9aa0ae;
}

/* 验证 */
::v-deep .verifyForm .el-form-item {
}
::v-deep .verifyForm .el-form-item__label {
  font-weight: 400;
  color: #666;
  font-size: 14px;
  line-height: 44px;
}
::v-deep .verifyForm .el-form-item__content {
  line-height: 44px;
}
::v-deep .verifyForm .el-input__inner {
  height: 44px;
  line-height: 44px;
}
::v-deep .verifyForm .el-input button {
  position: relative;
  border: 0;
  color: #f87a23;
  font-size: 14px;
}
::v-deep .verifyForm .el-input button:focus,
::v-deep .verifyForm .el-input button:hover {
  background-color: transparent;
}
::v-deep .verifyForm .el-input button::before {
  content: "";
  position: absolute;
  left: 0;
  width: 1px;
  height: 12px;
  background-color: #d3d3d3;
}

.setForm {
  margin-bottom: 80px;
}

/* 验证提示 */
.verifyHint {
  margin-bottom: 20px;
}
.verifyHint p {
  display: flex;
  align-items: center;
  font-size: 14px;
}
.verifyHint i {
  font-size: 20px;
  margin-right: 10px;
}
.verifyHint .vSuccess {
  color: #4fb256;
}

/* 确认按钮 */
.setBtn {
  position: absolute;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: flex-end;
  width: 100%;
  padding: 10px 30px;
  border-top: 1px solid #ecedf0;
  background-color: #fff;
}
.setBtn .el-button {
  padding: 0;
  width: 110px;
  padding: 10px 0;
  font-weight: bold;
  color: #999;
}
.setBtn .el-button.addBtn {
  border-color: #f87a23;
  background-color: #f87a23;
  color: #fff;
}
.setBtn .el-button:hover {
  border-color: #f87a23;
  color: #f87a23;
  background-color: transparent;
}
.setBtn .el-button.addBtn:hover {
  border-color: #f87a23;
  background-color: #f87a23;
  color: #fff;
  opacity: 0.9;
}
</style>

<style scoped>
/* 响应式 */
@media (max-width: 1120px) {
  .selectVerify ul > li{
    flex-wrap: wrap;
    padding: 12px;
  }
  .selectVerify ul > li .verifyIcon{
    width: 38px;
    height: 38px;
    margin-right: 10px;
  }
  .selectVerify ul > li .verifyInfo{
    width: calc(100% - 48px);
  }
  .selectVerify ul > li .verifyInfo > span{
    margin-top: 0;
  }
  .selectVerify ul > li .verifyInfo > p{
    font-size: 14px;
    word-wrap:break-word
  }

  .setBtn{
    padding: 10px 30px;
  }
  .setBtn .el-button{
    width: 80px;
    padding: 6px 0;
  }
}
</style>